package artid.com.arttogoa;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import artid.com.arttogoa.R;

import artid.com.arttogoa.adapter.GoodatAdapter;
import artid.com.arttogoa.adapter.StrericWheelAdapter;
import artid.com.arttogoa.app.ArtWorkApp;
import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.NormalItem;
import artid.com.arttogoa.parser.OtherInformationParser;
import artid.com.arttogoa.parser.OtherInformationParser.OtherInformationParser_good;
import artid.com.arttogoa.parser.OtherInformationParser.OtherInformationParser_university;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.AppUtil;
import artid.com.arttogoa.util.BitmapUtil;
import artid.com.arttogoa.util.CameraUtils;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.VioceUtils;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.view.WheelView;
import artid.com.arttogoa.volley.BitmapCache;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

import android.Manifest;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.animation.AnticipateOvershootInterpolator;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 完善信息
 * 
 * @author ksn
 *
 */
public class ImproveInformationActivity extends BaseActivity implements
OnClickListener {
	private TextView mOk, edit_native_placetext, school_data_text;
	private EditText info_memo;
	private MyEditText nameEd;
	private RelativeLayout edit_native_place, school_data, autograph_layout;
	private ImageView autograph_image;
	private String[] placeData = new String[34];
	private String[] schoolData=new String[10];
	private WheelView wheelView;
	private AlertDialog alertDialog;
	private GridView goodAtGrid;
	private ImageView voice;
	private String[] goodat = { "国画", "书法", "油画", "版画", "雕塑", "摄影", "当代艺术",
			"当代水墨", "水彩水粉", "其它" };
	private GoodatAdapter adapter;
	Boolean isSetPic = false;
	private Boolean isRegister=false;//是否是从注册过来的（默认false）
	private Boolean isFillInAutonym=false;//是否填写实名认证信息（默认false,判断注册使用）
	private ImageLoader mImageLoader;
	private Bitmap clipBitmap;//剪裁之后的图片
	private String Bitmap64;//剪裁之后的图片流
	private List<OtherInformationParser_good> list_good;
	private List<OtherInformationParser_university> list_university;
	private String PhotoPath;//剪裁之后的图片路径

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_improve_information);
		setContent(this, getIntent());
		//注册当前广播
		IntentFilter filter = new IntentFilter("com.ImproveInformationActivity.receiver");  
		registerReceiver(broadcastReceiver, filter);  
		ArtWorkApp.getInstance().addActivity(this);
		list_good=new ArrayList<OtherInformationParser_good>();
		list_university=new ArrayList<OtherInformationParser_university>();
		mTittle = (TextView) findViewById(R.id.title_text);
		mContext = this;
		isRegister=getIntent().getBooleanExtra("isRegister", false);
		isFillInAutonym=getIntent().getBooleanExtra("isFillInAutonym", false);
		mFbText = (TextView) findViewById(R.id.title_fb);
		mFbText.setOnClickListener(this);
		mFbText.setText("跳过");
		if(isRegister==false){
			mFbText.setVisibility(View.GONE);
		}
		RequestQueue mQueue = Volley.newRequestQueue(mContext);
		mImageLoader = new ImageLoader(mQueue, new BitmapCache());
		mOk = (TextView) findViewById(R.id.ImproveInformation_edit_ok);
		edit_native_place = (RelativeLayout) findViewById(R.id.ImproveInformation_edit_native_place);
		edit_native_place.setOnClickListener(this);
		school_data = (RelativeLayout) findViewById(R.id.ImproveInformation_school_data);
		school_data.setOnClickListener(this);
		autograph_layout = (RelativeLayout) findViewById(R.id.ImproveInformation_autograph_layout);
		autograph_layout.setOnClickListener(this);
		nameEd = (MyEditText) findViewById(R.id.ImproveInformation_nameEd);
		nameEd.setText(AppUtil.getUser().getRealname());
		edit_native_placetext = (TextView) findViewById(R.id.ImproveInformation_edit_native_placetext);
		school_data_text = (TextView) findViewById(R.id.ImproveInformation_school_data_text);
		info_memo = (EditText) findViewById(R.id.ed_info);
		nameEd.addTextChangedListener(mTextChangedListener);
		edit_native_placetext.addTextChangedListener(mTextChangedListener);
		school_data_text.addTextChangedListener(mTextChangedListener);
		info_memo.addTextChangedListener(mTextChangedListener);
		autograph_image = (ImageView) findViewById(R.id.ImproveInformation_autograph_image);
		mTittle.setText("完善信息");
		setBack();
		goodAtGrid = (GridView) findViewById(R.id.ImproveInformation_edit_gridview);
		voice=(ImageView) findViewById(R.id.iv_vioce);
		voice.setOnClickListener(this);
		initData();
		mBack.setOnClickListener(this);
		mOk.setOnClickListener(this);
		initplaceData();
		initschoolData();
		conditionJudge();
		//		getOtherInformation();
	}

	private void initData() {
		ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 10; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("goodat", goodat[i]);
			map.put("bo", false);
			lstImageItem.add(map);
		}

		adapter = new GoodatAdapter(mContext, lstImageItem);
		goodAtGrid.setAdapter(adapter);
	}

	private void initschoolData() {
		schoolData[0] = "中央美院";
		schoolData[1] = "中国美院";
		schoolData[2] = "鲁迅美院";
		schoolData[3] = "四川美院";
		schoolData[4] = "西安美院";
		schoolData[5] = "清华美院";
		schoolData[6] = "广州美院";
		schoolData[7] = "天津美院";
		schoolData[8] = "湖北美院";
		schoolData[9] = "其他";
	}

	private void initplaceData() {
		placeData[0] = "北京";
		placeData[1] = "天津";
		placeData[2] = "上海";
		placeData[3] = "重庆";
		placeData[4] = "河北";
		placeData[5] = "河南";
		placeData[6] = "云南";
		placeData[7] = "辽宁";
		placeData[8] = "黑龙江";
		placeData[9] = "湖南";
		placeData[10] = "安徽";
		placeData[11] = "山东";
		placeData[12] = "新疆维吾尔";
		placeData[13] = "江苏";
		placeData[14] = "浙江";
		placeData[15] = "江西";
		placeData[16] = "湖北";
		placeData[17] = "广西壮族";
		placeData[18] = "甘肃";
		placeData[19] = "山西";
		placeData[20] = "内蒙古";
		placeData[21] = "陕西";
		placeData[22] = "吉林";
		placeData[23] = "福建";
		placeData[24] = "贵州";
		placeData[25] = "广东";
		placeData[26] = "青海";
		placeData[27] = "西藏";
		placeData[28] = "四川";
		placeData[29] = "宁夏回族";
		placeData[30]="海南";
		placeData[31]="台湾";
		placeData[32]="香港";
		placeData[33]="澳门";
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.ImproveInformation_edit_ok:
			finishMessage();
			break;
		case R.id.ImproveInformation_edit_native_place:
			initAlertDialog(1);
			break;
		case R.id.ImproveInformation_school_data:
			initAlertDialog(2);
			break;
		case R.id.ImproveInformation_autograph_layout:
			showPopupWindow();
			break;
		case R.id.iv_vioce:
			VioceUtils vu = new VioceUtils(ImproveInformationActivity.this, voice, info_memo);
			vu.init();
			break;
		case R.id.title_fb:
			if(isFillInAutonym==true){
				//填写实名认证
				Intent i=new Intent(ImproveInformationActivity.this,RealNameAuthenticationTwoActivity.class);
				i.putExtra("isRegister", isRegister);
				startActivity(i);
			}else{
				//未填写实名认证
				Intent i=new Intent(this,LoginAvtivity.class);
				startActivity(i);
				ArtWorkApp.getInstance().exit();
			}
			break;
		default:
			break;
		}
	}

	public void showPopupWindow() {
		AlertUtils.initPhotoAlertDialog(mContext,Integer.parseInt(NetUtils.getDisplayMetrics(ImproveInformationActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.tv_phone:
					//检查权限
					if (ContextCompat.checkSelfPermission(ImproveInformationActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
						displayFrameworkBugMessageAndExit();
						return;
					}
					//照相机	
					CameraUtils.openCameraImage(ImproveInformationActivity.this);
					AlertUtils.dismiss();
					break;
				case R.id.tv_choice:
					//从相册获取
					CameraUtils.openLocalImage(ImproveInformationActivity.this);
					AlertUtils.dismiss();
					break;
				default:
					break;
				}
			}
		});
	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
		// TODO Auto-generated method stub  
		super.onActivityResult(requestCode, resultCode, data);  
		if (requestCode == CameraUtils.GET_IMAGE_BY_CAMERA) {
			final Uri uri=CameraUtils.imageUriFromCamera;
			if(uri != null) {
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath",  BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}else{
				//防止文件不会立马创建
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						if(uri != null) {
							Intent i=new Intent(mContext,Clip_Activity.class);
							i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
							startActivityForResult(i, 200);
						}
					}
				}, 1000);
			}
		} else if (requestCode == CameraUtils.GET_IMAGE_FROM_PHONE) {
			//判断是否从相册中获取图片
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				Intent i=new Intent(mContext,Clip_Activity.class);
				i.putExtra("ImagePath", BitmapUtil.UriConversionAbsoluteURL(mContext, uri));
				startActivityForResult(i, 200);
			}
		} else if(requestCode==200){
			//获取剪切后的图片路径
			if(data!=null){
				PhotoPath=data.getExtras().getString("PhotoPath");  
				if(!StringUtils.isEmpty(PhotoPath)){
					clipBitmap=BitmapUtil.getSmallBitmap(PhotoPath, 500, 500);
					//设置图片
					autograph_image.setImageBitmap(clipBitmap);
					Bitmap64= BitmapUtil.bitmaptoString(clipBitmap);
				}
			}
			conditionJudge();
		}
	}


	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   
			//对按钮的判断是否可用
			conditionJudge();
		}  
	};  

	/**
	 * 条件判断
	 */
	private void conditionJudge(){
		if(!StringUtils.isEmpty(nameEd.getText().toString()) && !"籍贯".equals(edit_native_placetext.getText().toString()) && 
				!StringUtils.isEmpty(Bitmap64)  && !"毕业学院".equals(school_data_text.getText().toString()) && 
				!StringUtils.isEmpty(info_memo.getText().toString())
				//				&& !StringUtils.isEmpty(adapter.getCheckedVal())	（根据需求暂时隐藏去掉擅长领域）
				){
			mOk.setEnabled(true);
			mOk.setBackgroundResource(R.drawable.red_frame);
		}else{
			mOk.setEnabled(false);
			mOk.setBackgroundResource(R.drawable.zjm_bg_dl);
		}
	}


	/**
	 * 提交信息
	 */
	private void finishMessage() {
		String goodat = adapter.getCheckedVal();//获取到的擅长领域
		VolleyBasic.getInstance(ImproveInformationActivity.this).post(
				Cache.perfectinformation,
				VolleyMap.getInstance().perfectInformation(
						edit_native_placetext.getText().toString(), Bitmap64,
						"",school_data_text.getText().toString(),
						StringUtils.replace(info_memo.getText().toString(),"\"","”"),nameEd.getText().toString()), NormalItem.class,
						new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						if(isFillInAutonym==true){
							//填写了实名认证信息
							Intent i=new Intent(ImproveInformationActivity.this,RealNameAuthenticationTwoActivity.class);
							i.putExtra("isRegister", isRegister);
							startActivity(i);
						}else{
							//未填写了实名认证信息
							Intent i=new Intent(ImproveInformationActivity.this,LoginAvtivity.class);
							startActivity(i);
							ArtWorkApp.getInstance().exit();
						}
						if(!StringUtils.isEmpty(PhotoPath)){
							BitmapUtil.deleteBitmap(PhotoPath);
						}
					}

					@Override
					public void onError(VolleyError volleyError) {

					}


				});

	}

	/**
	 * 动态获取学校和地区
	 */
	private void getOtherInformation(){
		VolleyBasic.getInstance(ImproveInformationActivity.this).post(
				Cache.otherInformation,
				VolleyMap.getInstance().otherInformation(), OtherInformationParser.class,
				new VolleyCallback() {
					@Override
					public void onSuccess(VolleyData vd) {
						OtherInformationParser parser=(OtherInformationParser) vd.getData();
						list_good=parser.getListGood();
						list_university=parser.getListUniversity();
						schoolData=new String[list_good.size()];
						for (int i = 0; i < list_good.size(); i++) {
							schoolData[i]=list_good.get(i).getTitle();
						}
					}

					@Override
					public void onError(VolleyError volleyError) {

					}


				});
	}

	private void initAlertDialog(final int type) {
		View view = LayoutInflater.from(ImproveInformationActivity.this)
				.inflate(R.layout.pop_menu_type, null);
		wheelView = (WheelView) view.findViewById(R.id.timeWheel);
		if (type == 1) {
			wheelView.setAdapter(new StrericWheelAdapter(placeData));
		} else if (type == 2) {
			wheelView.setAdapter(new StrericWheelAdapter(schoolData));
		}
		wheelView.setCurrentItem(2);
		wheelView.setCyclic(true);
		wheelView.setInterpolator(new AnticipateOvershootInterpolator());

		view.findViewById(R.id.btnCancel).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (alertDialog != null && alertDialog.isShowing()) {
							alertDialog.dismiss();
						}

					}
				});
		view.findViewById(R.id.btnConfirm).setOnClickListener(
				new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if (alertDialog != null && alertDialog.isShowing()) {
							if (type == 1) {
								edit_native_placetext.setText(wheelView
										.getCurrentItemValue());
							} else if (type == 2) {
								school_data_text.setText(wheelView
										.getCurrentItemValue());
							}
							alertDialog.dismiss();
						}

					}
				});

		alertDialog = new AlertDialog.Builder(ImproveInformationActivity.this)
		.create();
		alertDialog.show();

		WindowManager.LayoutParams params = alertDialog.getWindow()
				.getAttributes();
		params.width = ImproveInformationActivity.this.getWindowManager()
				.getDefaultDisplay().getWidth();
		int height = ImproveInformationActivity.this.getWindowManager()
				.getDefaultDisplay().getHeight();
		params.height = LayoutParams.WRAP_CONTENT;
		params.gravity = Gravity.BOTTOM;

		Window window = alertDialog.getWindow();
		window.setAttributes(params);
		window.setContentView(view);
		alertDialog.getWindow().setContentView(view);
	}

	//对开始接单的广播监听
	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {  

		@Override  
		public void onReceive(Context context, Intent intent) {  
			// TODO Auto-generated method stub  
			conditionJudge();
		}
	};

	/**
	 * 若摄像头被占用或者摄像头有问题则跳出提示对话框
	 */
	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("请设置开启摄像头权限");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				NetUtils.getAppDetailSettingIntent(mContext);
			}
		});
		builder.show();
	}

	protected void onDestroy() {
		super.onDestroy();
		//关闭广播
		unregisterReceiver(broadcastReceiver);
	};
}
